package flextv.search.logic {

import flextv.core.logic.Logger;
import flextv.core.logic.Util;
import flextv.search.vo.SearchItem;

import mx.logging.ILogger;
import mx.rpc.IResponder;
import mx.rpc.events.ResultEvent;
import mx.rpc.http.HTTPService;
	

public class SingleSearchItemServiceImpl implements ISingleSearchItemService {
	
	private static const LOG: ILogger = Logger.getLog(SingleSearchItemServiceImpl);
	
	/**
	 * @see http://code.google.com/apis/youtube/2.0/developers_guide_protocol.html#Retrieve_video_entry
	 */
	private static const BASE_URL: String = "http://gdata.youtube.com/feeds/api/videos/";
	
	public function SingleSearchItemServiceImpl() {
	}
	
	public function fetchNewSearchItemByYid(watchId: String, responder: IResponder): void {
		if(watchId == null || watchId.length == 0) throw new ArgumentError("Invalid watchId ["+watchId+"]!");
		 
		const requestUrl: String = BASE_URL + watchId;
		const httpService: HTTPService = new HTTPService();
		httpService.url = requestUrl; 
		
		// httpService.addEventListener(FaultEvent.FAULT, this._fnFault);
		httpService.addEventListener(ResultEvent.RESULT, function(event: ResultEvent): void {
			LOG.debug("onResult(event="+event+")");

		 	const item: SearchItem = entry2SearchItem(event.result.entry, watchId);
			responder.result(item);
		});
		 
		LOG.debug("httpService.send(requestUrl="+requestUrl+")");
		httpService.send();
		 
		 
	}

	private static function entry2SearchItem(entry: Object, yid: String): SearchItem {
		
		const title: String = entry.title;
		const duration: uint = entry.group.duration.seconds as uint;
		const thumbnailUrl: String = Util.extractFirstThumbnail(entry); 
		
		return new SearchItem(yid, title, duration, thumbnailUrl);
	}
	
}
}